﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace InseSoft.Infraestructure
{
    //Got this from Josh Smith's Crack .NET project at codeplex
    public class RelayCommand : ICommand
    {
        #region Declarations

        readonly Func<Boolean> canExecute;
        readonly Action execute;

        #endregion

        #region Constructors

        public RelayCommand(Action execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action execute, Func<Boolean> canExecute)
        {

            if (execute == null)
                throw new ArgumentNullException("execute");
            this.execute = execute;
            this.canExecute = canExecute;
        }

        #endregion

        #region ICommand Members

        public event EventHandler CanExecuteChanged
        {
            add
            {

                if (canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {

                if (canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        [DebuggerStepThrough]
        public Boolean CanExecute(Object parameter)
        {
            return canExecute == null || canExecute();
        }

        public void Execute(Object parameter)
        {
            execute();
        }

        #endregion
    }

    public class RelayCommandWithParameter : ICommand
    {
        #region Declarations

        readonly Func<Boolean> canExecute;
        readonly Action<object> execute;

        #endregion

        #region Constructors

        public RelayCommandWithParameter(Action<object> execute)
            : this(execute, null)
        {
        }

        public RelayCommandWithParameter(Action<object> execute, Func<Boolean> canExecute)
        {

            if (execute == null)
                throw new ArgumentNullException("execute");
            this.execute = execute;
            this.canExecute = canExecute;
        }

        #endregion

        #region ICommand Members

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        [DebuggerStepThrough]
        public Boolean CanExecute(Object parameter)
        {
            return canExecute == null || canExecute();
        }

        public void Execute(Object parameter)
        {
            execute(parameter);
        }

        #endregion
    }
}
